<template>
  <a-skeleton :loading="loading" active :title="false" :paragraph="{ rows: 6, width: '100%' }">
    <a-card hoverable :bordered="false" size="small">
      <a-table
        rowKey="id"
        size="small"
        :dataSource="dataSource"
        :columns="columns"
        :pagination="false"
        :onExpand="handldOnExpand"
        :indentSize="40"
        :scroll="{ x: 800 }"
        :key="new Date().getTime()"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'operation'">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span> 操作 </span>
              <a-button
                type="primary"
                size="middle"
                @click="addDept"
                v-auth="['admin', 'dept:add']"
              >
                新增
              </a-button>
            </div>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'enabled'">
            <span>
              <a-switch
                :disabled="record.id === 1"
                v-model:checked="record.enabled"
                @change="changeEnabled(record, record.enabled)"
              />
            </span>
          </template>
          <template v-if="column.key === 'operation'">
            <span>
              <a-button
                type="link"
                size="middle"
                @click="editDept(record)"
                v-auth="['admin', 'dept:edit']"
                >编辑</a-button
              >
              <a-divider type="vertical" />
              <a-popconfirm
                v-if="dataSource.length"
                title="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
                @confirm="onDelete(record.id)"
              >
                <a-button type="link" size="middle" v-auth="['admin', 'dept:del']">删除</a-button>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>

      <DeptModal ref="deptModalRef" />
    </a-card>
  </a-skeleton>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted, watch, createVNode } from 'vue';
  import { Modal, notification } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { reload, hasChildren } from './index';
  import { getDeptsApi, editDeptApi, delDeptApi } from '/@/api/dept';
  import DeptModal from './deptModal.vue';

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '排序',
      dataIndex: 'deptSort',
      key: 'deptSort',
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
    },
  ];

  export default defineComponent({
    components: {
      DeptModal,
    },
    setup() {
      const loading = ref<boolean>(true);
      const dataSource = ref<any>([]);
      const loadDepts = async () => {
        try {
          let res = await getDeptsApi({
            page: 0,
            size: 20,
            sort: 'id,desc',
          });
          dataSource.value = hasChildren(res?.content || []);
        } catch (error) {}
      };

      watch([reload], () => {
        loadDepts();
      });

      onMounted(() => {
        setTimeout(async () => {
          loading.value = false;
        }, 300);
        loadDepts();
      });

      const handldOnExpand = async (expanded, record) => {
        if (!expanded) return; //如果是关闭就返回
        if (record.children && record.children.length > 0) return; //如果已经有数据就返回
        const id = record.id;
        const data = dataSource.value;
        let response = await getDeptsApi({
          pid: id,
        });
        //获取到的子节点
        const children = hasChildren(response?.content ?? []);
        const dataMap = (items: Array<any>) => {
          items.find((item) => {
            if (item.id === id) {
              //找到当前要展开的节点
              item.children = children;
              return items;
            }
            if (item.children && item.children.length > 0) {
              dataMap(item.children);
            }
          });
        };
        dataMap(data || []);
        dataSource.value = data;
      };

      const deptModalRef = ref();
      const addDept = () => {
        deptModalRef.value.open(true, {});
      };
      const editDept = (record) => {
        deptModalRef.value.open(false, { ...record });
      };

      const changeEnabled = (data, val) => {
        Modal.confirm({
          title: '提示',
          icon: createVNode(ExclamationCircleOutlined),
          content: '此操作将' + (val ? '启用' : '禁用') + data.name + ', 是否继续？',
          async onOk() {
            try {
              await editDeptApi(data);
              notification['success']({
                message: '操作成功!',
                duration: 3,
              });
            } catch (error) {
              data.enabled = !data.enabled;
            }
          },
          onCancel() {
            data.enabled = !data.enabled;
          },
        });
      };

      const onDelete = async (id: number) => {
        try {
          await delDeptApi([id]);
          reload.value = !reload.value;
          notification['success']({
            message: '删除成功!',
            duration: 3,
          });
        } catch (error) {}
      };

      return {
        loading,
        handldOnExpand,
        dataSource,
        columns,
        deptModalRef,
        addDept,
        editDept,
        onDelete,
        changeEnabled,
      };
    },
  });
</script>
<style lang="less" scoped></style>
